<template>
  <div class="test-container page-container">
    <el-radio-group ref="tabRef" v-model="searchForm.status" style="margin-bottom: 10px" size="large" @change="changeStatus">
      <el-radio-button label="-1">全部</el-radio-button>
      <el-radio-button :label="1">未审核</el-radio-button>
      <el-radio-button :label="2">审核通过</el-radio-button>
      <el-radio-button :label="3">审核不通过</el-radio-button>
    </el-radio-group>
    <!-- 搜索选项 -->
    <el-row class="M-B-5" ref="searchRef">
      <el-form :inline="true" class="form" v-model="searchForm">
        <el-form-item class="Form-Item" label="">
          <el-select v-model="searchForm.userId" style="width:150px;" placeholder="请选择作者" clearable>
              <el-option v-for="(item,index) in userDrop" :key="index" :value="item.id" :label="item.username"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="Form-Item" label="">
          <el-select v-model="searchForm.order" style="width:160px;" placeholder="请选择排序方式" clearable>
              <el-option v-for="(item,index) in orderDrop" :key="index" :value="item.Value" :label="item.Key"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="Form-Item" label="">
          <el-select v-model="searchForm.timeType" style="width:100px;" placeholder="时间类型" clearable>
              <el-option v-for="(item,index) in timeTypeDrop" :key="index" :value="item.Value" :label="item.Key"></el-option>
            </el-select>
          <el-date-picker v-model="searchForm.sumTime" type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间" />
        </el-form-item>
        <el-form-item class="Form-Item" label="">
          <el-input class="W-Search" v-model="searchForm.searchWord"  placeholder="请输入关键词搜索" clearable >
            <template #prepend>
            <el-select v-model="searchForm.searchType" style="width:100px;" placeholder="关键词" clearable>
              <el-option v-for="(item,index) in searchTypeDrop" :key="index" :value="item.Value" :label="item.Key"></el-option>
            </el-select>
            </template>
          </el-input>
        </el-form-item>
      <el-button type="primary" @click="search">搜索</el-button>
      <el-button type="warning" @click="reset">重置</el-button>
      </el-form>
    </el-row>
    <!-- 按钮组 -->
    <el-row class="M-B-5" ref="btnsRef">
      <el-button type="primary" @click="batchAudit(null,2)" >批量过审</el-button>
      <el-button type="primary" @click="batchAudit(null,3)" >批量驳回</el-button>
      <el-button type="danger" @click="batchDel" >批量删除</el-button>
    </el-row>
    <!-- 表格 -->
    <el-row class="M-B-5" >
      <el-table :data="tableData" stripe style="width: 100%" border highlight-current-row :height="tableHeight" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column v-for="(item,index) in tableCols" :key="index" :prop="item.prop" :label="item.label" :min-width="item.minWidth">
          <template  #default="scope">
            <!-- 作者 -->
            <div v-if="item.prop=='authorId'">{{ toUserName(scope.row.authorId) }}</div>
            <!-- 性别 -->
            <div v-if="item.prop=='gender'">{{ scope.row.gender == 1?'男':scope.row.gender == 2?'女':'未知' }}</div>
            <!-- 话题 -->
            <div v-if="item.prop=='topic'">
              <el-tooltip
                class="box-item"
                effect="dark"
                :content="topicList.length && toTopic(scope.row.topic)"
                placement="bottom"
              >
              <div class="P-Line-1">{{ topicList.length && toTopic(scope.row.topic)}}</div>
              </el-tooltip>
            </div>
            <!-- 标签 -->
            <div v-if="item.prop=='tags'">
              <el-tooltip
                class="box-item"
                effect="dark"
                :content="tagsList.length && toTags(scope.row.tags)"
                placement="bottom"
              >
              <div class="P-Line-1">{{ tagsList.length && toTags(scope.row.tags) }}</div>
              </el-tooltip>
            </div>
            <!-- 状态 -->
            <div v-if="item.prop=='status'">
              <el-tag class="M-R-5" :type="scope.row.status==1?'info':scope.row.status==2?'success':scope.row.status==3?'danger':''">{{scope.row.status==1?'待审核':scope.row.status==2?'审核通过':scope.row.status==3?'未过审':''}}</el-tag>
            </div>
            <!-- 操作 -->
            <div v-if="item.prop=='handle'">
              <el-button size="small" type="primary" @click="view(scope)">查看</el-button>
              <el-button size="small" v-if="scope.row.status===1" type="success" @click="batchAudit(scope.row,2)">通过</el-button>
              <el-button size="small" v-if="scope.row.status===1" type="info" @click="batchAudit(scope.row,3)">驳回</el-button>
              <el-button size="small" type="danger" @click="batchDel(scope.$index, scope.row)" >删除</el-button>
            </div>
            <!-- 角色 -->
            <div v-if="item.prop=='roles'">
              <el-tooltip
                class="box-item"
                effect="dark"
                :content="getRoleNames(scope.row.roles)"
                placement="bottom"
              >
              <div class="P-Line-1">{{getRoleNames(scope.row.roles)}}</div>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <!-- 分页 -->
    <el-row ref="pageRef">
      <el-pagination
      :total="pageTotal"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 20, 50]"
      :background="pageBackground"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    </el-row>
    <addUser ref="addUserRef" @RefreshListEmit ="reset"/>
    <el-dialog v-model="viewModel" :title="viewTitle" width="800" >
        <div v-html="content" style="height: 550px;overflow-y: auto;">
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="cencelView">关闭</el-button>
          </span>
        </template>
      </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref,reactive ,toRefs ,onMounted,nextTick,defineAsyncComponent } from 'vue'
import { getUsersApi,deleteUsersApi,changeStatusApi } from '@/request/user'
import { articleListApi,auditArticleApi,deleteArticleApi } from '@/request/article'
import { tagsListApi } from '@/request/tag'
import { topicListApi } from '@/request/topic'
import { rolelistApi } from '@/request/role'
import { getCurrentInstance} from 'vue'
import {useStore} from '@/store'
import article from '@/config/Enums/article'
import Pinterface from '@/config/Interface/Public'
import Interface from '@/config/Interface/Article'
import addUser from '@/components/user/addUser.vue'
export default defineComponent({
  name: 'Vuex',
  components:{addUser},
  setup() {
    const context = getCurrentInstance()?.appContext.config.globalProperties; //获取this
    const store = useStore()
    const reactiveData = reactive({
      // 表单
      searchForm:{
        userId:'',
        order:'',
        searchWord:'',
        searchType:'',
        timeType:'',
        sumTime:['',''],
        status:'-1',
        },
      // 表头
      tableCols:[
        {prop:'title',label:'标题',minWidth:140},
        {prop:'authorId',label:'作者',minWidth:100},
        {prop:'topic',label:'话题',minWidth:125},
        {prop:'tags',label:'标签',minWidth:125},
        {prop:'status',label:'状态',minWidth:80},
        {prop:'like_count',label:'点赞数',minWidth:80},
        {prop:'view_count',label:'浏览量',minWidth:80},
        {prop:'create_time',label:'创建时间',minWidth:168},
        {prop:'audit_time',label:'审核时间',minWidth:168},
        {prop:'handle',label:'操作',minWidth:220},
      ],
      // 表格数据项
      tableData:[],
      //下拉
      searchTypeDrop:context?.$enums.GetEnumArr(article.searchTypeDrop),
      orderDrop:context?.$enums.GetEnumArr(article.orderDrop),
      StatusDrop:context?.$enums.GetEnumArr(article.StatusDrop),
      timeTypeDrop:context?.$enums.GetEnumArr(article.timeTypeDrop)
    })
    const userDrop =  ref([])
    // 获取用户列表(下拉)
    const getUserList = async () =>{
      const res = await getUsersApi({all:true})
      if(res.data.code === 1){
        userDrop.value = res.data.data
      }
    }

    // 获取文章列表
    const getArticleList = async () =>{
      const orederArr:Pinterface.KeyVal[] = [
        {Key:'timeAsc',Value:1},
        {Key:'timeDesc',Value:2},
        {Key:'likeAsc',Value:3},
        {Key:'likeDesc',Value:4},
        {Key:'viewAsc',Value:5},
        {Key:'viewDesc',Value:6},
      ]
      const orderTpye = orederArr.find((item:any)=>(item.Value == reactiveData.searchForm.order))
      const postData = {
        pageSize:pageSize.value,
        currentPage:currentPage.value,
        ...reactiveData.searchForm,
        sumTime:reactiveData.searchForm.sumTime || ['',''],
        order:reactiveData.searchForm.order? orderTpye && orderTpye.Key :''
      }
      const res = await articleListApi(postData)
      if(res.data.code === 1){
        reactiveData.tableData=res.data.data.data.filter((item:any)=>(item.status!==0))
        pageTotal.value = res.data.data.total
      }
    }

    // 切换状态
    const changeStatus = () =>{
      getArticleList()
    }



    // 搜索
    const search = ()=>{
      getArticleList()
    }
    // 重置
    const reset = () =>{
      reactiveData.searchForm.userId=''
      reactiveData.searchForm.order=''
      reactiveData.searchForm.searchWord=''
      reactiveData.searchForm.searchType=''
      reactiveData.searchForm.timeType=''
      reactiveData.searchForm.sumTime=['','']
      reactiveData.searchForm.status='-1'
      currentPage.value = 1;
      search()
    }

    // dom节点
    const searchRef = ref();
    const btnsRef = ref();
    const pageRef = ref();
    const tabRef = ref();

    //表格高度
    const tableHeight = ref(0);

    // 分页
    const currentPage = ref(1)
    const pageSize = ref(10)
    const pageTotal = ref(0)
    const pageBackground = ref(false)

    // 切换表格显示条数
    const handleSizeChange = (val: number) => {
      pageSize.value= val;
      getUserList()
    }

    // 切换页码
    const handleCurrentChange = (val: number) => {
      currentPage.value = val
      getUserList()
    }

    // 获取表格高度
    const getTableHeight = ()=>{
      nextTick(()=>{
        if(store!==undefined){
          tableHeight.value = context?.$utils.getTableHeight(store.state.cardHeight,[searchRef.value.$el,btnsRef.value.$el,pageRef.value.$el,tabRef.value.$el])
        }else{
          tableHeight.value = 653;
        }
      })
    }

    //表格多选列表
    const selections = ref<any[]>([])
    const handleSelectionChange = (val: any[]) => {
      selections.value = val
    }
    const addUserRef = ref()
    // 创建
    const add = (Type:string,scope?:any) => {
      addUserRef.value.trigger(Type,scope)
    }

    // 查看
    const viewModel = ref(false)
    const viewTitle = ref('')
    const content = ref('')
    const view = (scope:any) =>{
      viewModel.value = true
      content.value = scope.row.content
      viewTitle.value = scope.row.title
    }

    // 关闭查看
     const cencelView = () =>{
      viewModel.value = false
      viewTitle.value = ''
      content.value = ''
     }

    const batchAudit = async (row:any,targetStatus:number)=>{
      let ids:number[] = []
      if(row){
        ids = [row.id]
      }else{
        if(!selections.value.length){
          ElMessage({
            message:"请先选择数据",
            type:"warning"
          })
          return
        }
        if(selections.value.find((item:any)=>(item.status!==1))){
          ElMessage({
            message:"请先选择待审核的文章",
            type:"warning"
          })
          return
        }
        ids = selections.value.map(item=>item.id)
      }
      const postData = {ids,targetStatus}
      const res = await auditArticleApi(postData)
      if(res.data.code === 1){
        const msg = targetStatus==2?'审核成功':'驳回成功'
        ElMessage({
          message:msg,
          type:"success"
        })
        reset()
      }
    }

    // 删除 批量删除
    const batchDel = async (index?:any,row?:any) => {
      let ids:number[] = []
      if(row){
        ids = [row.id]
      }else{
        if(!selections.value.length){
          ElMessage({
            message:"请先选择数据",
            type:"warning"
          })
          return
        }
        ids = selections.value.map(item=>item.id)
      }
      ElMessageBox.confirm(
        '确定删除？','删除用户',
        {confirmButtonText: '确定',cancelButtonText: '取消',type: 'error',}
      ).then(async () => {
        const postData = {ids}
        const res = await deleteArticleApi(postData)
        if(res.data.code === 1){
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          reset()
        }
      }).catch(() => {

      })
    }

    // 作者转名字
    const toUserName = (id:number) => {
      const user = userDrop.value.find((item:any)=>(item.id == id))
      if(user){
        return (user as any).username
      }else{
        return ''
      }
    }

    // 标签列表
    const tagsList = ref([])
    const getTagsList = async () => {
      const {data} = await tagsListApi({all:true})
      if(data.code === 1){
        tagsList.value = data.data
        console.log(tagsList.value);
      }
    }

    // 话题列表
    const topicList = ref([])
    const getTopicList = async() => {
      const {data} = await topicListApi({all:true})
      if(data.code === 1){
        topicList.value = data.data
        console.log(topicList.value);
      }
    }

    const toTags = (tagIds:string) =>{
      const tagsArr = tagIds.split(',')
      const tagsNameArr:any = []
      tagsList.value.forEach((item:any)=>{
        tagsArr.forEach((data:any)=>{
          if(item.id == Number(data)){
            tagsNameArr.push(item.tag_name)
          }
        })
      })
      return tagsNameArr.join(',')
    }

    const toTopic = (topicIds:string) =>{
      const topicsArr = topicIds.split(',')
      const topicsNameArr:any = []
      topicList.value.forEach((item:any)=>{
        topicsArr.forEach((data:any)=>{
          if(item.id == Number(data)){
            topicsNameArr.push(item.topic_name)
          }
        })
      })
      return topicsNameArr.join(',')
    }

    // 挂载
    onMounted(()=>{
      getUserList()
      getTableHeight()
      getArticleList()
      getTagsList()
      getTopicList()
    })

    return {
      ...toRefs(reactiveData),
      searchRef,btnsRef,pageRef,tabRef,
      tableHeight,getTableHeight,getUserList,
      currentPage,pageSize,pageTotal,pageBackground,handleSizeChange,handleCurrentChange,
      search,reset,add,batchDel,
      handleSelectionChange,
      addUserRef,
      userDrop,toUserName,changeStatus,batchAudit,
      viewModel,content,view,viewTitle,cencelView,
      getTagsList,getTopicList,topicList,tagsList,
      toTopic,toTags
    }
  }
})
</script>

<style scoped lang="stylus">

</style>
